package com.fileFormatConvert;

import java.io.*;

public class FileUtils {
    public static boolean saveFile(byte[] bytes, String path, String fileName) {
        File directory = new File(path);

        // Check if the directory exists, if not, create it
        if (!directory.exists()) {
            if (!directory.mkdirs()) {
                System.err.println("Failed to create the directory: " + path);
                return false;
            }
        }

        // Create the file object
        File file = new File(directory, fileName);

        // Write the byte array to the file
        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(bytes);  // Save the byte array to the file
            System.out.println("File saved successfully to: " + file.getAbsolutePath());
            return true;  // Return true if the file is saved successfully
        } catch (IOException e) {
            System.err.println("Error saving file: " + e.getMessage());
            return false;  // Return false if there is an error
        }
    }

    public static boolean saveFile(OutputStream outputStream, String path, String fileName) {
        File directory = new File(path);
        // Check if the directory exists, if not, create it
        if (!directory.exists()) {
            if (!directory.mkdirs()) {
                return false;
            }
        }
        // Create the file object
        File file = new File(directory, fileName);

        // Now let's write the content of the OutputStream to the file
        try (FileOutputStream fos = new FileOutputStream(file)) {
            // If the outputStream is a ByteArrayOutputStream, we can simply get the byte array
            if (outputStream instanceof ByteArrayOutputStream) {
                byte[] data = ((ByteArrayOutputStream) outputStream).toByteArray();
                fos.write(data);
            } else {
                // For other types of OutputStream, you might need to copy content manually
                return false;
            }
            return true;
        } catch (IOException e) {
            return false;
        }
    }
}
